package com.dmz.etc.task.service;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.extra.ftp.Ftp;
import com.dmz.etc.task.config.DmzProp;
import com.dmz.etc.task.config.EnvConfig;
import com.dmz.etc.task.config.enums.RecordCode;
import com.dmz.etc.task.domain.Msg20511003;
import com.dmz.etc.task.mapper.ServerMapper;
import com.dmz.etc.task.utils.FileUtil;
import com.dmz.etc.task.utils.etc.DateTools;
import com.dmz.etc.task.utils.ftp.FtpClient;
import com.dmz.etc.task.utils.ftp.FtpFile;
import com.dmz.etc.task.utils.ftp.FtpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author lee
 */
@Service
@Slf4j
public class FileService {

    @Autowired
    private DmzProp dmzProp;

    @Autowired
    private ServerMapper serverMapper;

    public boolean parseFile() throws IOException {
        Ftp ftp = new FtpClient().cspFtp();
        //2051  充值对账文件发送通知报文
        String endStr = EnvConfig.getProperty("ftp.file.fileName.end");
        String fileName2051 = EnvConfig.getProperty("ftp.file.fileName.cz2051").replace("{yesterday}", DateTools.getYesterday()).replace("{today}", DateTools.getDateStr())
                + DateTools.getTimeStr() + endStr;
        String cspFileName = EnvConfig.getProperty("csp.file.fileName").replace("{date}", DateTools.getDateStr()).replace("{yesterday}", DateTools.getYesterday());

        String remotePath = EnvConfig.getProperty("csp.file.path");
        String localPath = EnvConfig.getProperty("ftp.file.path.temp");
        FtpFile file2051 = new FtpFile(ftp, remotePath + cspFileName, localPath + fileName2051, fileName2051);
        log.info(file2051.toString());
        boolean b = FtpUtil.download(file2051);
        if(b) {
            log.info("下载文件成功{}", file2051);
            FtpUtil.close(ftp);
            File file = FileUtil.file(file2051.getLocalPath());
            try{
                String date = DateTools.getYesterday();
                processFile1(file, date);
            }catch (IOException e) {
                log.info("处理文件报错：{}", e.getMessage());
                throw new IOException(e);
            }
            return uploadFile(file2051);
        }else {
            return false;
        }

    }

    private boolean uploadFile(FtpFile file) {
        String fileName = file.getFileName();
        String localPath = file.getLocalPath();
        try (Ftp dmzFtp = new FtpClient().dmzFtp()) {
            String dmzPath = EnvConfig.getProperty("dmz.file.path");
            FtpFile dmzFile = new FtpFile(dmzFtp, dmzPath, localPath, fileName);
            FtpUtil.upload(dmzFile);
            log.info("文件上传成功！");
            FtpUtil.close(dmzFtp);
            //FileUtil.del(localPath);
            //log.info("临时文件删除成功{}", localPath);
            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }


    private void processFile1(File file, String date) throws IOException {
        String encoding = dmzProp.getDefaultEncoding();

        String dateTime = date + DateTools.getTimeStr();
        List<String> newLines = new CopyOnWriteArrayList<>();
        List<Msg20511003> data = new ArrayList<>();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file, encoding).getReader())) {
            String line;
            int l = 0;
            while ((line = bufferedReader.readLine()) != null) {
                l ++;
                if(l > 1) {
                    String[] records = line.split("\\|");
                    List<Msg20511003> ms = serverMapper.queryData3003(records[1].trim(), date);
                    data.addAll(ms);
                }
            }
        } catch (IOException e) {
            // 处理IOException，例如记录日志或抛出运行时异常
            throw new IOException("Failed to read file", e);
        }

        long czTotalMoney = 0;
        long czMoney = 0;
        long qcMoney = 0;
        long moneycz = 0;
        long bkMoney = 0;
        long tkMoney = 0;

        if (!data.isEmpty()) {
            czTotalMoney = data.stream().mapToLong(Msg20511003::getCzTotalMoney).sum();
            czMoney = data.stream().mapToLong(Msg20511003::getCzMoney).sum();
            qcMoney = data.stream().mapToLong(Msg20511003::getQcMoney).sum();
            moneycz = data.stream().mapToLong(Msg20511003::getMoneyCz).sum();
            bkMoney = data.stream().mapToLong(Msg20511003::getBkMoney).sum();
            tkMoney = data.stream().mapToLong(Msg20511003::getTkMoney).sum();
        }

        String bt = EnvConfig.getProperty("ftp.file.bt").replace("{fileName}", file.getName()).replace("{date}", dateTime);
        newLines.add(bt);
        String zbt1 = RecordCode.CODE_3001.getCode() + "|1|i|";
        newLines.add(zbt1);
        StringBuilder sb3001 = new StringBuilder();
        sb3001.append(date).append("|")
                .append(dmzProp.getBankId()).append("|")
                .append(dmzProp.getBankName()).append("|")
                .append(czTotalMoney).append("|")
                .append(czMoney).append("|")
                .append(qcMoney).append("|")
                .append(moneycz).append("|")
                .append(bkMoney).append("|")
                .append(tkMoney).append("|")
                .append(DateTools.getDateTimeString()).append("|");
        newLines.add(sb3001.toString());
        String zbt2 = RecordCode.CODE_3002.getCode() + "|1|i|";
        newLines.add(zbt2);
        StringBuilder sb3002 = new StringBuilder();
        sb3002.append(date).append("|")
                .append(dmzProp.getBankId()).append("|")
                .append(dmzProp.getBankName()).append("|")
                .append(dmzProp.getNetworkId()).append("|")
                .append(dmzProp.getTerminalId()).append("|")
                .append(czTotalMoney).append("|")
                .append(czMoney).append("|")
                .append(qcMoney).append("|")
                .append(moneycz).append("|")
                .append(bkMoney).append("|")
                .append(tkMoney).append("|")
                .append(dateTime).append("|");
        newLines.add(sb3002.toString());
        String zbt3 = RecordCode.CODE_3003.getCode() + "|"+ data.size() +"|i|";
        newLines.add(zbt3);
        for (Msg20511003 m : data) {
            StringBuilder sb = new StringBuilder();
            sb.append(m.getWasteSn()).append("|")
                    .append(m.getDateTime()).append("|")
                    .append(m.getNetworkId()).append("|")
                    .append(m.getTerminalId()).append("|")
                    .append(m.getCzType()).append("|")
                    .append(m.getCustomerId()).append("|")
                    .append(m.getPCardNetId()).append("|")
                    .append(m.getPCardId()).append("|")
                    .append(m.getOnlineSn()).append("|")
                    .append(m.getOfflineSn()).append("|")
                    .append(m.getRandom()).append("|")
                    .append(m.getMac1()).append("|")
                    .append(m.getMac2()).append("|")
                    .append(m.getSysBeforeMoney()).append("|")
                    .append(m.getCardBeforeMoney()).append("|")
                    .append(m.getCzTotalMoney()).append("|")
                    .append(m.getCzMoney()).append("|")
                    .append(m.getQcMoney()).append("|")
                    .append(m.getMoneyCz()).append("|")
                    .append(m.getBkMoney()).append("|")
                    .append(m.getTkMoney()).append("|")
                    .append(m.getAfterMoney()).append("|")
                    .append(m.getCzResult()).append("|")
                    .append(m.getNote()).append("|");
            newLines.add(sb.toString());
        }
        FileUtil.clean(file);
        FileUtil.writeLines(newLines, file, encoding, false);
        log.info("文件生成成功：{}", file.getName());
    }

    public boolean parseFile(String date) throws IOException {
        Ftp ftp = new FtpClient().cspFtp();
        //2051  充值对账文件发送通知报文
        String endStr = EnvConfig.getProperty("ftp.file.fileName.end");
        String fileName2051 = EnvConfig.getProperty("ftp.file.fileName.cz2051").replace("{yesterday}", date).replace("{today}", date)
                + DateTools.getTimeStr() + endStr;
        String cspFileName = EnvConfig.getProperty("csp.file.fileName").replace("{date}", date).replace("{yesterday}", date);

        String remotePath = EnvConfig.getProperty("csp.file.path");
        String localPath = EnvConfig.getProperty("ftp.file.path.temp");
        FtpFile file2051 = new FtpFile(ftp, remotePath + cspFileName, localPath + fileName2051, fileName2051);
        log.info(file2051.toString());
        boolean b = FtpUtil.download(file2051);
        if(b) {
            log.info("下载文件成功{}", file2051);
            FtpUtil.close(ftp);
            File file = FileUtil.file(file2051.getLocalPath());
            try{
                processFile1(file, date);
            }catch (IOException e) {
                log.info("处理文件报错：{}", e.getMessage());
                throw new IOException(e);
            }
            return uploadFile(file2051);
        }else {
            return false;
        }

    }
}
